#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
//#include "Terminal.hpp"
using namespace std;

void Usage(string proc)
{
    cout<<"\n\rUsage:"<<proc<<" serverip serverport\n"<<endl;
}

struct ThreadData{
    struct sockaddr_in sever;
    int sockfd;
    string severip;
};

void *recv(void* args)
{
       // OpenTerminal();
        ThreadData* td=static_cast<ThreadData*> (args);
        char buffer[1024];
        while (true)
        {
            memset(buffer,0,sizeof(buffer));
            struct sockaddr_in temp;
            socklen_t len=sizeof(temp);
            ssize_t s=recvfrom(td->sockfd,buffer,1023,0,(struct sockaddr*)&temp,&len);
            if(s>0)
            {
                buffer[s]=0;
                cerr<<buffer<<endl;
            }
        } 
}

void *send(void* args)
{
        ThreadData* td=static_cast<ThreadData*>(args);
        string message;
        socklen_t len=sizeof(td->sever);
        string welcome=td->severip;
        welcome+=" coming ...";
        sendto(td->sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&(td->sever),len);
        while(true)
        {
            cout<<"Plese Enter@";
            getline(cin,message);
            sendto(td->sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&(td->sever),len);
        }
}

int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(0);
    }
        string severip=argv[1];
        uint16_t severport=stoi(argv[2]);
        struct ThreadData td;
        bzero(&td.sever,sizeof(td.sever));
        td.sever.sin_family=AF_INET;
        td.sever.sin_addr.s_addr=inet_addr(severip.c_str());
        td.sever.sin_port=htons(severport);
        td.sockfd=socket(AF_INET,SOCK_DGRAM,0);
        if(td.sockfd<0)   
        {
            cout<<"socke error"<<endl;
            return 1;
        }
        td.severip=severip;
        pthread_t recvr,sender;
        pthread_create(&recvr,nullptr,recv,&td);
        pthread_create(&sender,nullptr,send,&td);
        pthread_join(recvr,nullptr);
        pthread_join(sender,nullptr);
        return 0;
}